/**
 * 微信聊天时间显示规则
 * 1.当天的消息，以每5分钟为一个跨度的显示时间
 * 2.消息超过1天、小于1周，显示星期+收发消息的时间
 * 3.消息大于1周，显示手机收发时间的日期
 * @params date 时间戳
 */

const formatChatDate = (date) => {
    const now = Date.now();
    const y1 = new Date(date).getFullYear();
    const y2 = new Date().getFullYear();
    const m1 = new Date(date).getMonth() + 1;
    const m2 = new Date().getMonth() + 1;
    const d1 = new Date(date).getDate();
    const d2 = new Date().getDate();
    const h =
        new Date(date).getHours() > 9
            ? new Date(date).getHours()
            : "0" + new Date(date).getHours();
    const m =
        new Date(date).getMinutes() > 9
            ? new Date(date).getMinutes()
            : "0" + new Date(date).getMinutes();
    const week = ["日", "一", "二", "三", "四", "五", "六"];
    const w = new Date(date).getDay();
    // 0.
    if (now < new Date(date).getTime()) {
        return (
            y2 +
            "年" +
            m1 +
            "月" +
            d1 +
            "日 " +
            new Date().getHours() +
            ":" +
            new Date().getMinutes()
        );
    }
    // 1.
    if (y1 === y2 && m1 === m2 && d1 === d2) {
        return h + ":" + m;
    }
    // 2.
    const dis =
        new Date(y2 + "/" + m2 + "/" + d2).getTime() -
        new Date(y1 + "/" + m1 + "/" + d1).getTime();
    const aday = 24 * 60 * 60 * 1000;
    const aweek = 7 * aday;
    if (dis >= aday && dis < aday * 2) {
        return `昨天 ${h}:${m}`;
    }
    if (dis >= aday * 2 && dis < aweek) {
        return "星期" + week[w] + " " + h + ":" + m;
    }
    // 3.
    return y1 + "年" + m1 + "月" + d1 + "日 " + h + ":" + m;
};

export default formatChatDate;
